<?php
/**
 * Created by IntelliJ IDEA.
 * User: ahwwl
 * Date: 18-4-2
 * Time: 上午11:18
 */

namespace app\controller;


use app\model\AgentList;
use app\model\CardList;
use app\model\CardPackageList;
use app\model\OrderList;
use app\model\UserCardList;
use app\model\UserList;
use app\model\WalletLog;
use think\Db;
use think\Request;

/**
 * @property UserList UserList
 * @property UserCardList UserCardList
 * @property OrderList OrderList
 * @property WalletLog WalletLog
 * @property AgentList AgentList
 * @property CardList CardList
 * @property CardPackageList CardPackageList
 */
class Agentcommon extends CommonController
{
    function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->UserList = new UserList();
        $this->UserCardList = new UserCardList();
        $this->OrderList = new OrderList();
        $this->WalletLog = new WalletLog();
        $this->AgentList = new AgentList();
        $this->CardList = new CardList();
        $this->CardPackageList = new CardPackageList();
    }

    function agent_card_list()
    {
        $this->assign("page_title","代理卡列表");
        return $this->fetch();
    }
    function ajax_agent_card_list()
    {
        try
        {
            if($this->agent_id<1)
            {
                exception("非客户");
            }
            $page = input("page",1,"intval");
            $rows = input("rows",30,"intval");
            $mobile = input("mobile","","trim");
            $real_name = input("real_name","","trim");
            $card_no = input("card_no","","trim");

            $where = [];
            if(!empty($mobile))
                $where["b.mobile"] = $mobile;
            if(!empty($real_name))
                $where["b.real_name"] = ["like",$real_name."%"];
            if(!empty($card_no))
                $where["a.card_no"] = ["like","%".$card_no."%"];
            $where["a.agent_id"] = $this->agent_id;
            $count = $this->UserCardList->alias("a")
                ->join("f_user_list b","a.user_id=b.id","left")
                ->where($where)
                ->count();
            $page_total = ceil($count/$rows);
            $page = $page>$page_total?$page_total:$page;
            $page = $page < 1? 1:$page;
            $order_log = $this->UserCardList->alias("a")
                ->join("f_user_list b","a.user_id=b.id","left")
                ->join("f_agent_list al" ,"al.id=a.agent_id","left")
                ->join("f_company_list cl" ,"cl.id=a.company_id","left")
                ->field("a.*,b.real_name,b.mobile,al.agent_name,cl.name as company_name")
                ->where($where)
                ->order("a.id desc")
                ->limit(($page-1)*$rows,$rows)
                ->select();
            $user_card_idle_list = $this->UserCardList->where(["user_id"=>0,"card_type"=>["GT",0]])->select();
            $this->resultdata["user_card_idle_list"] = $user_card_idle_list;
            $this->resultdata["data"] = $order_log;
            $this->resultdata["error"] = 0;
            $this->resultdata["total"] = $count;
            $this->resultdata["page"] = $page;
            $this->resultdata["rows"] = $rows;
        }catch (\Exception $e)
        {

            $this->resultdata["msg"] = $e->getMessage();
        }

        echo json_encode($this->resultdata);
    }

    function agent_order_list()
    {
        $this->assign("page_title","代理卡列表");
        return $this->fetch();
    }
    function ajax_agent_order_list()
    {
        try
        {
            if($this->agent_id<1)
            {
                exception("非客户");
            }
            $page = input("page",1,"intval");
            $rows = input("rows",30,"intval");
            $order_no = input("order_no","","trim");
            $third_no = input("third_no","","trim");
            $card_no = input("card_no","","trim");
            $user_mobile = input("user_mobile","","trim");
            $mode = input("mode",-1,"intval");
            $mobile = input("mobile","","trim");
            $pay_type = input("pay_type",0,"intval");
            $pay_status = input("pay_status",0,"intval");
            $delivery_status = input("delivery_status",0,"intval");
            $status = input("status",0,"intval");
            $date_1 = input("date_1",get_date_time("Y-m-d"),"trim");
            $date_2 = input("date_2",get_date_time("Y-m-d"),"trim");
            if($date_1 > $date_2)
                $this->E("选择日期出错");

            $date_1 = strtotime($date_1);

            if(empty($date_1))
                $date_1 = strtotime("today");
            $date_2 = strtotime($date_2);
            if(empty($date_2))
                $date_2 = strtotime("today");
            $where = [];
            if(in_array($mode,[0,1]))
                $where["ol.mode"] = $mode;
            if(!empty($order_no))
                $where["ol.order_no"] = $order_no;
            if(!empty($third_no))
                $where["ol.third_no"] = $third_no;
            if(!empty($card_no))
                $where["ol.card_no"] = $card_no;
            if(!empty($user_mobile))
                $where["ul.mobile"] = $user_mobile;
            if(!empty($mobile))
                $where["ol.mobile"] = $mobile;
            if(in_array($pay_type,[0,1,2]))
                $where["ol.pay_type"] = $pay_type;
            if(in_array($pay_status,[0,1,2,3,4]))
                $where["ol.pay_status"] = $pay_status;
            if(in_array($delivery_status,[0,1,2,3]))
                $where["ol.delivery_status"] = $delivery_status;
            if(in_array($status,[0,1,2,3]))
                $where["ol.status"] = $status;
            $where["ol.ctime"] = ["between",[$date_1,$date_2+86400-1]];
            $where["ol.is_delete"] = 0;
            $where["ol.agent_id"] = $this->agent_id;
            $count = $this->OrderList->alias("ol")
                ->join("f_user_list ul","ul.id=ol.user_id","left")
                ->join("f_card_package_list cpl","cpl.id=ol.product_id","left")
                ->where($where)
                ->count();
            $page_total = ceil($count/$rows);
            $page = $page>$page_total?$page_total:$page;
            $page = $page < 1? 1:$page;
            $order_log = $this->OrderList->alias("ol")
                ->join("f_user_list ul","ul.id=ol.user_id","left")
                ->join("f_card_package_list cpl","cpl.id=ol.product_id","left")
                ->join("f_agent_list al","al.id=ol.agent_id","left")
                ->where($where)
                ->field("ol.discount_code,ol.ctime,ol.callback_time,ol.order_no,ol.third_no,ol.card_no,ol.card_type,ol.basic_price,ol.money,ol.freight,ol.card_fee,ol.total_money,ol.mode,ol.pay_type,ol.pay_status,ol.status,ol.delivery_status")
                ->field("ul.mobile as user_mobile,cpl.name as product_name,al.agent_name")
                ->order("ol.ctime desc")
                ->limit(($page-1)*$rows,$rows)
                ->select();

            $money_list = $this->OrderList->alias("ol")
                ->join("f_user_list ul","ul.id=ol.user_id","left")
                ->join("f_card_package_list cpl","cpl.id=ol.product_id","left")
                ->join("f_agent_list al","al.id=ol.agent_id","left")
                ->where($where)
                ->field(['sum(ol.total_money) as count_total_money',
                    'sum(if(ol.status=2,ol.cost,0)) as count_cost',
                    'sum(if(ol.status=2,ol.card_fee,0)) as count_card_fee',
                    'sum(if(ol.status=2,ol.total_money-ol.card_fee-ol.cost,0)) as count_profit',
                    'sum(if(ol.pay_type=3,ol.supply_cost,0)) as count_pay_supply_cost',
                    'sum(ol.supply_cost) as count_supply_cost'
                ])
                ->find();
            $this->resultdata["money_list"] = $money_list;
            $this->resultdata["data"] = $order_log;
            $this->resultdata["error"] = 0;
            $this->resultdata["total"] = $count;
            $this->resultdata["page"] = $page;
            $this->resultdata["rows"] = $rows;
        }catch (\Exception $e)
        {

            $this->resultdata["msg"] = $e->getMessage();
        }

        echo json_encode($this->resultdata);
    }
    function agent_rebate_list()
    {
        $this->assign("page_title","代理卡列表");
        return $this->fetch();
    }
    function ajax_agent_rebate_list()
    {
        try
        {
            if($this->agent_id<1)
            {
                exception("非客户");
            }
            $page = input("page",1,"intval");
            $rows = input("rows",30,"intval");
            $order_no = input("order_no","","trim");
            $date_1 = input("date_1",get_date_time("Y-m-d"),"trim");
            $date_2 = input("date_2",get_date_time("Y-m-d"),"trim");
            if($date_1 > $date_2)
                $this->E("选择日期出错");

            $date_1 = strtotime($date_1);

            if(empty($date_1))
                $date_1 = strtotime("today");
            $date_2 = strtotime($date_2);
            if(empty($date_2))
                $date_2 = strtotime("today");
            $where = [];
            if(!empty($order_no))
                $where["order_no"] = $order_no;
            $where["type"] = 1;
            $where["ctime"] = ["between",[$date_1,$date_2+86400-1]];

            $where["agent_id"] = $this->agent_id;
            $count = $this->WalletLog
                ->where($where)
                ->count();
            $page_total = ceil($count/$rows);
            $page = $page>$page_total?$page_total:$page;
            $page = $page < 1? 1:$page;
            $order_log = $this->WalletLog
                ->where($where)
                ->order("ctime desc")
                ->limit(($page-1)*$rows,$rows)
                ->select();
            $query = $this->WalletLog
                ->where($where)
                ->field("sum(money) as count_money")
                ->find();
            $count_money = !empty($query)?intval($query["count_money"]):0;




            $this->resultdata["count_money"] = $count_money;
            $this->resultdata["data"] = $order_log;
            $this->resultdata["error"] = 0;
            $this->resultdata["total"] = $count;
            $this->resultdata["page"] = $page;
            $this->resultdata["rows"] = $rows;
        }catch (\Exception $e)
        {

            $this->resultdata["msg"] = $e->getMessage();
        }

        echo json_encode($this->resultdata);
    }
    function agent_card_charge()
    {
        if($this->agent_id<1)
        {
           $this->error("非客户");
        }
        $agent_info = $this->AgentList->where(["status"=>0,"id"=>$this->agent_id])->find();
        $package_list = $this->CardPackageList->where(["status"=>0,"card_type"=>0])->select();
        $this->assign("agent_info",$agent_info);
        $this->assign("package_list",$package_list);
        $this->assign("page_title","充值卡充值");
        return $this->fetch();
    }
    function ajax_agent_card_charge()
    {
        try
        {
            if($this->agent_id<1)
            {
                exception("非客户");
            }
            $card_no_list = input("card_no_list","","trim");
            $amount = input("amount",0,"intval");
            $card_type = 0;
            if(empty($card_no_list)||empty($amount))
                $this->E("参数不正确");
            if(($amount%100)>0)
                exception("amount is error",102);
            $card_no_list = explode("\n",$card_no_list);

            foreach($card_no_list as $key=>$val)
            {
                $card_no_list[$key] = trim($val);
                if(strlen($card_no_list[$key]) != 19)
                    exception("卡号19位");
            }
            if($card_type == 0)
            {
                $count = $this->CardList->where(["card_no" =>["in",$card_no_list]])->count();
                if($count>0)
                    exception("非普通卡",102);
            }
            $agent_info = $this->AgentList->where(["id"=>$this->agent_id])->find();
            if(empty($agent_info))
                exception("代理信息不存在",102);
            $money_discount = $agent_info["money_discount"];
            $basic_price = $amount;
            $mode           = 0;
            $package_info = $this->CardPackageList->where(["status"=>0,"mode"=>$mode,"card_type"=>$card_type,"basic_price"=>$basic_price])->find();
            if(empty($package_info))
                exception("当前面额不存在",102);
            $basic_price = $package_info["basic_price"];
            $cost = $package_info["cost"];
            $money = $package_info["money"];
            if($money_discount>0)
                $money = $basic_price*$money_discount;
            $total_money = $money;
            $all_order_info = [];
            $all_wallet_info = [];
            $all_total_money = 0;
            foreach ($card_no_list as $card_no)
            {
                $order_no       = get_order_no("D",$card_no);
                $info = [
                    "order_no"      => $order_no,
                    "agent_id"      => $this->agent_id,
                    "card_no"       => $card_no,
                    "card_type"     => $card_type,
                    "basic_price"   => $basic_price,
                    "cost"          => $cost,
                    "money"         => $money,
                    "total_money"   => $total_money,
                    "mode"          => $mode,
                    "pay_type"      => 4,
                    "pay_status"    => 1,
                    "ctime"         => NOW_TIME,
                    "mtime"         => NOW_TIME,
                    "ip"            => $this->request->ip(),
                    "token_type"    => 0,
                ];
                $wallet_info = [
                    "agent_id"=>$this->agent_id,
                    "order_no"=>$order_no,
                    "type"=>2,
                    "money"=>-$total_money,
                    "info"=>"代理充值：".$card_no,
                    "ctime"=>NOW_TIME
                ];
                $all_order_info[] = $info;
                $all_wallet_info[] = $wallet_info;
                $all_total_money += $total_money;
            }

            Db::startTrans();
            try{
                $query = $this->AgentList->where(["id"=>$this->agent_id])->where("(balance+credit)>=".$all_total_money)->setDec("balance",$all_total_money);
                if(empty($query))
                    exception("余额不足",102);
                $query = $this->OrderList->insertAll($all_order_info);
                if(empty($query))
                    exception("添加订单失败",102);

                $query = $this->WalletLog->insertAll($all_wallet_info);
                if(empty($query))
                {
                    exception("流水添加失败");
                }
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                exception($e->getMessage(),$e->getCode());
            }
            foreach ($all_order_info as $val)
            {
                $order_no = $val["order_no"];
                sendMQQueue("fuel_order_recharge",$order_no);
            }

            $this->resultdata["error"] = 0;

        }catch (\Exception $e)
        {

            $this->resultdata["msg"] = $e->getMessage();
        }

        echo json_encode($this->resultdata);
    }


}